package logic

import (
	"context"
	"errors"
	"fmt"
	"math/rand"
	"shell/model/cache"
	"shell/model/mysql"
	"shell/pkg"

	"shell/shellrpc/internal/svc"
	"shell/shellrpc/shellrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *shellrpc.LoginRequest) (*shellrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	var users mysql.User
	mysql.DB.Debug().Where("tel = ?", in.Tel).Find(&users)
	result, _ := cache.Rdb.Get(l.ctx, "Captcha"+in.Tel).Result()
	if result != in.Captcha {
		return nil, errors.New("验证码错误，请重新输入")
	}
	if users.ID == 0 {
		user := mysql.User{
			Tel:       in.Tel,
			Password:  pkg.MD5(in.Password),
			HeadImage: "https://bpic.588ku.com/original_origin_min_pic/19/10/04/a321f23dd346c61646a546ad9cc9194d.jpg!r650",
			UserName:  fmt.Sprintf("用户_%d", rand.Intn(9000)),
			UserSign:  in.UserSign,
		}
		err := mysql.DB.Debug().Create(&user).Error
		if err != nil {
			return nil, err
		}
	} else {
		if pkg.MD5(in.Password) != users.Password {
			return nil, errors.New("密码错误，请重新输入")
		}
	}

	return &shellrpc.LoginResponse{
		UserId: int64(users.ID),
	}, nil
}
